<?php

namespace app\admin\controller;

use app\admin\controller\Base;
use app\common\model\FileLog;
use app\common\model\VisitShow;
use app\common\model\YearCard;
use think\facade\View;
use think\facade\Config;
use think\facade\Cache;


class Yearcards extends Base
{
    // 轮播列表
    public function cardList()
    {
        if (request()->IsAjax()) {
            $get = $this->request->get();
            $limit = isset($get['limit']) && $get['limit'] ? $get['limit'] : 10;
            $page = isset($get['page']) && $get['page'] ? $get['page'] : 1;
            $yearCardModel = new YearCard();
            $sort = 'status asc';
            $cardlist = $yearCardModel->getPagelist([], '', $sort, $limit, $page);

            foreach($cardlist as $key=>$val){
                if($val['status'] == 1){
                    $cardlist[$key]['status'] = "已使用";
                }else{
                    $cardlist[$key]['status'] = "未使用";
                }
            }
            $count = $yearCardModel->countRows([]);
            return json(["code" => 0, "msg" => '成功', "count" => $count, "data" => $cardlist]);
        } else {
            return View::fetch();
        }
    }
    // 发布轮播
    public function saveCard()
    {
        if (request()->IsAjax()) {
            $post = $this->request->post();
            if(empty($post['num'])){
                return json(['code' => 0, 'msg' => '生成数量不能为空']);
            }

            $add = [];
            for($i= 0;$i < $post['num'];$i++){
                $add[] = [
                    "status" =>0,
                    "created_at" =>date("Y-m-d H:i:s"),
                    "update_at" =>date("Y-m-d H:i:s"),
                    "number" =>uniqid(),
                ];
            }
        
            // 新增
            try {
                YearCard::insertAll($add);
                return json(['code' => 1, 'msg' => '新增成功']);
            } catch (\Exception $e) {
                $msg = $e->getMessage();
                return json(['code' => 0, 'msg' => '新增失败']);
            }
        } else {
            return View::fetch();
        }
    }
    // 删除轮播
    public function delCard()
    {
        if (request()->IsAjax()) {
            $post = $this->request->post();
            if (isset($post['id']) && $post['id']) {
                try {
                    YearCard::destroy($post['id']);
                    return json(['code' => 1, 'msg' => '删除成功']);
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json(['code' => 0, 'msg' => '删除失败']);
                }
            } else {
                return json(['code' => 0, 'msg' => '缺少参数']);
            }
        }
    }
 
}
